<template>
  <!-- @focus="focus" -->
  <a-tree-select
    @change="change"
    showSearch
    style="width: 100%"
    :treeCheckable="true"
    v-model="selectDep"
    :treeData="treeData"
    :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
    placeholder="请选择"
    allowClear
    :disabled="disabled"
    treeDefaultExpandAll
  />
</template>

<script>
  // import { mapState } from 'vuex'
  const treeData = []
  var setValue = arr => {
    for (let i = 0; i < arr.length; i++) {
      arr[i].value = arr[i].key
      if (arr[i].children.length > 0) {
        setValue(arr[i].children, arr[i].key, arr[i].title)
      }
    }
    return arr
  }
  // 对比之前选择的部门 如果之前没有选择过部门 则把所有的部门都设为可选
  var compareSelected = (keyArr, arr) => {
    for (let i = 0; i < arr.length; i++) {
      if (keyArr.indexOf(arr[i].key) > -1) {
        arr[i].disabled = true
        arr[i].selectable = false
      } else {
        arr[i].disabled = false
        arr[i].selectable = true
      }
      if (arr[i].children.length) {
        compareSelected(keyArr, arr[i].children)
      }
    }
  }
  export default {
    name: 'depTreeSelect',
    data() {
      return {
        // selectDep: '',
        treeData: [],
        selectDep: [],
      }
    },
    props: {
      // mulSelect: {
      //   type: Boolean,
      //   default: false,
      //   required: false,
      // },
      disabledList: {
        type: Array,
        default: () => {
          return []
        },
        required: false,
      },
      disabled: {
        type: Boolean,
        default: false,
        required: false,
      }
      // selectDep: {
      //   type: [Number, String, Array],
      //   default: null,
      //   required: false,
      // },
    },
    watch: {
      selectDep(val) {
        let treeData = this.$store.state.SysDepartment.treeData
        treeData = setValue(treeData)
        if (treeData.length > 0) {
          treeData.forEach(v => (v.disabled = true))
        }
        this.treeData = treeData
        if (val === 0) {
          this.selectDep = treeData[0].key
        }
      },
    },
    methods: {
      change(value) {
        // this.selectDep = value
        this.$emit('getValue', value)
      },
      clear() {
        this.selectDep = null
      },
      // focus() {
      //   let treeData = JSON.parse(JSON.stringify(this.treeData))
      //   // if (this.disabledList.length > 0) {
      //   compareSelected(this.disabledList, treeData)
      //   this.treeData = treeData
      //   // }
      // },
    },
    created() {
      let treeData = this.$store.state.SysDepartment.treeData
      treeData = setValue(treeData)
      if (treeData.length > 0) {
        // 把所有根节点选择都设置为不可选择，因为所有的根节点都是租户
        treeData.forEach(v => (v.disabled = true))
      }
      this.treeData = treeData
    },
  }
</script>
